/**
 * https://www.bilibili.com/video/BV1Mb411e7re/?p=7
 * 根据原理图可看出:
 * 独立按键K1, K2, K3, K4 分别连接了'TXD', 'RXD', P32, P33
 * 当按键没按下时, 根据'独立按键原理图'可知, 这4个io口都是高电平
 * 当按键按下时, 这4个引脚变成低电平,
 * 所以, 需要写程序监视这4个io口的电平变化
 * 
 * 视频的独立按键S1是P3_1, TX-1C是S2: P3_4口
 */
#include <REGX52.H>
#include <INTRINS.H>
#include "Link/Delay_Utils.h"
#include "Link/Single_Keyboard_Utils.h"
#include "Link/Timer0_Utils.h"


//独立按键K1控制Led亮灭. 按下亮, 松手熄灭
void main_press_light() {
    while(1) {
        //K1连接的是'RXD', 是'P3_1'引脚
//        if(P3_1 == 0) { //如果K1按下
//            /**
//             * 位寄存器, 最低位的led灯,
//             * 不要使用P2 = 0xFE; 这样会给整个P2寄存器赋值
//             */
//            P2_0 = 0;
//        } else {
//            P2_0 = 1;
//        }
        
        P1_0 = P3_4;    //直接赋值
    }
}

/**
 * https://www.bilibili.com/video/BV1Mb411e7re/?p=8
 * 独立按键, 去抖动
 * 按下 --> 松开 --> 开灯/关灯
 */
void main_unShake_toggle() {
    static unsigned char keyNum;
    // while(1) {
        keyNum = 0;
        keyNum = Single_Keyboard_Down_Delay(1);
        if (keyNum == 1) P1_0 = ~P1_0;   //开灯/关灯
    // }
}

/**
 * https://www.bilibili.com/video/BV1Mb411e7re/?p=9
 * 独立按键, 去抖动
 * 按下 --> 松开 --> P2的8个灯展示二进制++
 */
void main_unShake_pp() {
    unsigned char keyNum;
    unsigned char i = 0;    //0~255,  0000 0000~ 1111 1111
    while(1) {
        keyNum = Single_Keyboard_Down_Delay(1);
        if (keyNum == 1) {
            /**
             * P2 刚开始默认高电平: 1111 1111
             * 第1个灯亮: 1111 1110
             */
            i++;
            P1 = ~i;
        }
    }
}

/**
 * https://www.bilibili.com/video/BV1Mb411e7re/?p=10
 * 独立按键, 去抖动
 * 按下 --> 松开 --> P2的8个灯展示二进制'左右移位'
 */
void main_unShake_move() {
    unsigned char keyNum;
    unsigned char i = 0;
    P1 = 0xFE;
    while(1) {
        keyNum = Single_Keyboard_Down_Delay(1);
        if (keyNum == 1) {
            i ++;
            if(i >= 8) i = 0;
            //P2: 1111 1111  ->  1111 1110  ->  1111 1101
            P1 = ~(1 << i);
        } else if(keyNum == 2) {
            if(i <= 0) i = 8;
            i --;
            P1 = ~(1 << i);
        }
    }
}


static void Timer0_onTick();
/**
 * 定时器扫描独立按键, 实现流水灯, 参考"13.AT24C02_IIC.c"
 */
void main_water_light() {
    //每15ms溢出1次
    Timer0_Init(15000, 0);
    Timer0_setOnTickListener_Exact(1, &Timer0_onTick);
    P1 = 0xFE;
     while (1);
}
static void Timer0_onTick() {
    static unsigned char count, key = 1;
    count ++;
    //每15ms调用1次
    Single_Keyboard_Down_Timer(1);

    //15*33 = 495ms滚动1次
    count++;
    if (count >= 33) {
        count = Single_Keyboard_Down_Timer_Get();
        //只算1&2, 0和其它不算
        if (count == 1 || count == 2) key = count;
        count = 0;
        if (key == 1) P1 = _crol_(P1, 1);
        else if(key == 2) P1 = _cror_(P1, 1);
    }
}